package com.jhd.fuzhou.util;

import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.view.login.LoginActivity;
import com.jhd.fuzhou.view.login.MainActivity;
import com.jhd.fuzhou.vo.AuthToken;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.UserMessage;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.io.IOException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;

import static com.xuexiang.xui.XUI.getContext;

public class NetInterceptor implements Interceptor {
    private FuzhouApplication application;

    public NetInterceptor(FuzhouApplication application) {
        this.application = application;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);//执行请求
        //String responseBodyStr = handResponse(response);//获得处理后的数据字符串
        if (response.code() == 401 || response.code() == 403) {//判断是否token过期
            String username = application.getUserName();
            String password = application.getPassword();

            if (username == null || password == null) return response;
            Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//new Retrofit.Builder().baseUrl(UtilHelper.baseUrls.API).addConverterFactory(FastJsonConverterFactory.create()).build();
            LoginService vs = retrofit.create(LoginService.class);
            Map<String, String> params = ParamsMapUtil.getInstance("username", username)
                    .addParam("password", password).addParam("type", "password");

            Call<JsonForResult> jsonForResultCall = vs.getAuthInfo(params);
            JsonForResult jsonForResult = jsonForResultCall.execute().body();
            if (jsonForResult != null && jsonForResult.isSuccess()) {
                AuthToken authToken = JSON.parseObject(jsonForResult.getData().toString(), AuthToken.class);
                if (authToken == null || StringUtil.isNullOrEmpty(authToken.getAccessToken())) {
                    throw new IOException("登录token过期,请注销重新登录!");
                }
                String accessToken = authToken.getAccessToken();
                application.setAccessToken(accessToken);
                application.setUserId(authToken.getAccessTokenByKey("userId").toString());
                getPersonInfo();
                Request newRequest = request.newBuilder().header("Authorization", application.getAccessToken()).build();
                response.body().close();
                return chain.proceed(newRequest);
            } else {
                if(jsonForResult != null && !jsonForResult.isSuccess()){//用户名或密码错误
                    if(jsonForResult.getMessage()!=null){
                        CustomToast.showText(getContext(),jsonForResult.getMessage(),3000,0,0).show();
                    }
                    application.clear();
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().startActivity(intent);
                    System.exit(0);
                }else{
                    throw new IOException(jsonForResult.getMessage());
                }
            }
        }else if(response.code()==409){
            application.clear();
            Intent intent = new Intent(getContext(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
            System.exit(0);
        } else if (response.code() > 300) {
            String error = "接口调用没有成功!http编码:" + response.code();
            if (StringUtil.isNullOrEmpty(response.message()) == false) {
                error = error + "." + response.message();
            }
            throw new IOException(error);
        }
        return response;
    }

    private void getPersonInfo(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("sysUserId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getPersonInfo(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, retrofit2.Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            UserMessage userMessage=JSON.parseObject(jsonForResult.getData().toString(), UserMessage.class);
                            application.setName(userMessage.getName());
                            application.setGender(userMessage.getGender());
                            application.setAssistant(userMessage.getAssistant());
                            application.setBirthday(userMessage.getBirthday());
                            application.setCity(userMessage.getCity());
                            application.setCounty(userMessage.getCounty());
                            application.setCreateTime(userMessage.getCreateTime());
                            application.setCreateUser(userMessage.getCreateUser());
                            application.setDeptName(userMessage.getDeptName());
                            application.setDeptId(userMessage.getDeptId());
                            application.setId(userMessage.getId());
                            application.setIdNo(userMessage.getIdNo());
                            application.setJoinSuperviseWork(userMessage.getJoinSuperviseWork());
                            application.setMobileActivateStatus(userMessage.getMobileActivateStatus());
                            application.setMobileNo(userMessage.getMobileNo());
                            application.setMobileRegisterStatus(userMessage.getMobileRegisterStatus());
                            application.setOrgId(userMessage.getOrgId());
                            application.setOrgName(userMessage.getOrgName());
                            application.setProvince(userMessage.getProvince());
                            application.setStatus(userMessage.getStatus());
                            application.setSysUserId(userMessage.getSysUserId());
                            application.setUseSystem(userMessage.getUseSystem());
                            application.setLawEnforceNo(userMessage.getLawEnforceNo());
                        }
                    } else {
                        //UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    //CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                //UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}